<script setup>
import register from "../api/register.js"
import {
Right,
Back
} from '@element-plus/icons-vue'
import imageShow from "./imageShow.vue"
import login from '../api/login.js'
import {useRouter} from 'vue-router'
import {ref , reactive} from 'vue';
import { useUserStore  } from '../stores/user'
import { Plus , Search , ArrowRightBold} from '@element-plus/icons-vue'
import updateUserInform from '../api/registerUserInform.js'
import confirm from '../api/confirm.js'
import sender from '../api/sendConfirmCode.js'
  
  const flag = ref(0)
  if(localStorage.getItem("jwttoken")!=null)
  {
    flag.value++
  }
  const image_id = ref("")
  const url = ref("http://localhost:5173/api/image/upload?token=Bearer " + localStorage.getItem("jwttoken"))
  const confirmCode_flag = ref(false)
  let userInform = useUserStore();
  userInform.clearStyle()
  const user = reactive([
    {
      username : "" ,
      password : "" 
    }
  ])
  const timeOut = ref(0)
  const imageUrl = ref("")
  const ruleFormRef = ref()
  const ruleFormRef2 = ref()
  const use = useRouter();
  let center = 0 ;
  const confirm_Flag = ref(false)
  // if(localStorage.getItem("userId")!=undefined)
  // {
  //   use.push("/");
  // }

  const userRegister = reactive({
    email :"" ,
    username : "" ,
    password : "" ,
    confirmPassword : "" ,
    birthDate : "" ,
    fullName : "" ,
    address : "" ,
    code : "" ,
  });

  const userInformSet = reactive({
    userName : "" ,
    imageId : "" 
  })

  const rules = reactive({
    email:[{ required: true, message: '请填写Email', trigger: 'blur' },
    { pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: '请输入有效的Email地址', trigger: 'blur' }],
    code:[{ required: true, message: '请填写Email', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '请填入验证码', trigger: 'blur' },
    {validator: validateConfirmCode , message:"验证码错误" , trigger: 'blur'}],
    username:[{ required: true, message: '不能为空', trigger: 'blur' },
    { min: 8, max:20 , message: '长度在8到20之间', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_-]+$/, message: '名称只能由字母、数字、下划线、连字符组成', trigger: 'blur' }],
    password:[{ required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在 8 到 20 个字符之间', trigger: 'blur' },
    { pattern: /^[\w-.]+$/, message: '密码只能由字母、数字、特殊字符组成', trigger: 'blur' }],
    confirmPassword:[{ required: true, message: '请输入密码', trigger: 'blur' },
    {validator: validatePassword ,message:"两次输入密码不同" , trigger: 'blur'}],
    birthDate: [{ required: true, message: '请输入日期', trigger: 'blur' },],
    fullName :[{ required: true, message: '请输入账户名', trigger: 'blur' },
    {min:2,max:16,message:'姓名长度为2到16 个字符之间',trigger: 'blur' }],
    address :[{ required: true, message: '输入一个地址', trigger: 'blur' },
    ]
  })

  const rules2 = reactive({
    username:[{ required: true, message: '不能为空', trigger: 'blur' },
    { min: 1, max:24 , message: '长度在1到24之间', trigger: 'blur' }],
  })


  const error_message = () => {
  ElMessage({message:'请检查信息是否出现错误。例如，验证密码与密码不相同.',
  type:"error"})
  }

  function confirmCodeFunc(){
      if(confirm_Flag.value) return true;
      confirm(userRegister.email,userRegister.code).then((res)=>{
        if(res.status == "200")
        {
          confirm_Flag.value = true
          return true;
        }
        else {
          return false ;
        }
      })

    }

    function validatePassword(rule, value, callback) {
    if (value !== userRegister.password) {
      callback(new Error("两次密码不相同"))
    } else {
      return true;
    }
    }
    function validateConfirmCode(rule, value, callback) {
    if (value === "" || value === undefined) {
      callback(new Error("验证码错误"))
    } else {
      return confirm_Flag.value
    }
    }


  const submit_register1 =  (formEl) => {
  if (!formEl) return
    formEl.validate((valid) => {
    if (valid) {
      request();
    } else {  
      error_message()
    }
  })
  }

  const submit_register2 = (formEl) => {
    if (!formEl) return
    formEl.validate((valid) => {
    if (valid) {
      userInformSet.imageId = image_id.value
      updateUserInform(
        userInformSet.userName ,
        userInformSet.imageId

      ).then((res)=>{
        if (res.status == 200) {
          flag.value ++ ;
          use.push("/")
        }
        else{
          ElMessage.error("上传失败")
        }
      })
      
    } else {  
      error_message()
    }
  })
  }

  function msToDate (msec) {
    let datetime = new Date(msec);
    let year = datetime.getFullYear();
    let month = datetime.getMonth();
    let date = datetime.getDate();
    let hour = datetime.getHours();
    let minute = datetime.getMinutes();
    let second = datetime.getSeconds();

    let result1 = year + 
                '-' + 
                ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                '-' + 
                ((date + 1) < 10 ? '0' + date : date) + 
                ' ' + 
                ((hour + 1) < 10 ? '0' + hour : hour) +
                ':' + 
                ((minute + 1) < 10 ? '0' + minute : minute) + 
                ':' + 
                ((second + 1) < 10 ? '0' + second : second);

    let result2 = year + 
                '-' + 
                ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) + 
                '-' + 
                ((date + 1) < 10 ? '0' + date : date);

    let result = {
        hasTime: result1,
        withoutTime: result2
    };

    return result;
}



  function request (){
      register({
        username : userRegister.username ,
        password : userRegister.password ,
        birthDate :  msToDate(userRegister.birthDate).withoutTime,
        fullName : userRegister.fullName ,
        address : userRegister.address, 
        email : userRegister.email,
        code : userRegister.code 
      }).then(function (response) {
        if(response.data.jwttoken == undefined || response.data.jwttoken == null || response.data.jwttoken == "")
        {
          error_message()
        }
        else
        {
          console.log(response.data.jwttoken)
          localStorage.setItem("jwttoken",response.data.jwttoken);
          flag.value ++ ;
        }
      })
    
    }
    
    function back () {
      use.back() ;
    }

    function forward() {
      use.push("/login");
    }

    function successHandler (res,file){
        image_id.value =res

        imageUrl.value = URL.createObjectURL(file.raw);
    }
    function beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 4;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 4MB!');
        }


        return isJPG && isLt2M;
      }

      function timerHandler_register () {
          setInterval(()=>{timeOut.value--},1000)
      }

      function sendConfirmCode(){
        if(userRegister.email.trim === "" || userRegister.email == undefined || userRegister.email === "")
        {
          ElMessage({message:'请输入邮箱',
          type:"error"})
          return null
        }
        sender(userRegister.email).then(
        (res)=>{
          if( res.status == "200" ){
              timeOut.value = 180
              timerHandler_register()
          }
        }
        )
      }
      if (flag >= 3) {
        use.push("/")
      }
</script> 

<template>
<div class="bg">
<nav> 
  <el-link :underline="false" size="large" style="position: relative; left: 2%; top: 1.8rem;" @Click="back"  ><el-icon color ="white" size="large"><Back /></el-icon></el-link>
  <el-link :underline="false" @Click="forward" style="position: fixed; top: 2.3rem; right: 6rem; text-align: center; color: #fff;" >已有账号？登录：<el-icon color ="white" size="large"><Right /></el-icon></el-link>
</nav>

  <div class="register-form">
    <div class="step">     
    <el-steps :active="flag" finish-status="success" simple style="margin-top: 20px">
    <el-step title="账目密码注册" />
    <el-step title="个人信息编辑" />
    <el-step title="个人偏好编辑" />
  </el-steps>
  </div>
  <div class="forms">
  <div class="form-box" v-if="flag == 1">
    <el-form style="margin-left: 10%;" :model="userRegister" ref="ruleFormRef" :rules="rules" :size="formSize" @submit.native.prevent>
      <el-form-item prop="email">
      <input type="text" v-model="userRegister.email" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>邮箱:</label>

      </el-form-item>

      <el-form-item prop="code">
      <input style="width:140px" type="text" v-model="userRegister.code" @blur="confirmCodeFunc" required>
      <label>验证码:</label>
      <span v-show="timeOut>0" style="margin-left:4%; margin-top:-1% ; color : #999" >有效时间:{{ timeOut }}</span>
      <el-button v-show="timeOut<=0" style="margin-left:3%" @click="sendConfirmCode()" round plain >  发送 </el-button>
      </el-form-item>


      <!--          后续补齐         -->
      <el-form-item prop="username">
      <input type="text" v-model="userRegister.username" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>账户(不可更改):</label>
      </el-form-item>
      <el-form-item prop="password">
      <input v-model="userRegister.password" type="password" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>密码:</label>
      </el-form-item>
      <el-form-item prop="confirmPassword">
      <input v-model="userRegister.confirmPassword" type="password" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>确认密码:</label>
      </el-form-item>
      <el-form-item prop="birthday">
      <el-date-picker v-model="userRegister.birthDate" type="date"  placeholder="出生年月日"  :size="size"/>
      <br>
      </el-form-item>
      <el-form-item prop="fullName">
      <input type="text" v-model="userRegister.fullName" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>姓名:</label>
      </el-form-item>
      <el-form-item prop="address">
      <input type="text" v-model="userRegister.address" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>地址:</label>
      </el-form-item>
      <el-form-item >
        <el-button type="info" @Click="submit_register1(ruleFormRef)" style="width: 10vw; bottom:-4%;  left: 15%; position: relative;" round plain>确定</el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="form-box two_box" v-if="flag == 2">
    <el-form style="margin-left: 10%;" :model="userInformSet" ref="ruleFormRef2" :rules="rules2" :size="formSize" @submit.native.prevent>
      <el-form-item prop="userName">
      <input type="text" v-model="userInformSet.userName" required>
      <span class="highlight"></span>
      <span class="bar"></span>
      <label>用户名:</label>
      </el-form-item>
      <el-form-item prop="password">
        <label> 上传头像: </label>
        <el-upload
        class="uploader_box avatar-uploader"
        :action="url"
        :show-file-list="true"
        :on-success = "successHandler"
        :before-upload="beforeAvatarUpload">
        <imageShow v-if="image_id" :value="image_id" class="avatar"></imageShow>
        <el-icon v-else class="el-icon-plus avatar-uploader-icon"> <Plus></Plus> </el-icon>
      </el-upload>
      </el-form-item>
    <el-form-item >
        <el-button type="info" @Click="submit_register2(ruleFormRef2)" style="width: 10vw; bottom:-4%; left: 15%; position: relative;" round plain>确定</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="form-box">
    
  </div>
</div>
  </div>


</div>


</template>

<style>
  @import url("@/css/login.css");
  @import url("@/css/input.css");
</style>
